﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace BoutiquePOS.DAL.Gateway
{
    public class CommonGateway: DbGateway
    {
        public string NextID(string yearAndMonth)
        {
            try
            {
                var table = new DataTable();

                string sql = "Select max(PurchaseNo) From PosPurchaseDtls";
                CommandObj.Parameters.Clear();
                CommandObj.CommandText = sql;
                ConnectionObj.Open();
                SqlDataAdapter ad = new SqlDataAdapter(CommandObj);
                ad.Fill(table);
                string id = table.Rows[0][0].ToString();
                if (id == "")
                {
                    string dd = "000001";
                    return yearAndMonth + dd;
                }
                else
                {
                    string temp;
                    int Nonzero;
                    int length;
                    string currentMaxId = table.Rows[0][0].ToString().Trim();
                    string lastSixDigit = currentMaxId.Substring(6, 6);
                    temp = lastSixDigit.ToString().Trim();
                    Nonzero = Convert.ToInt32(lastSixDigit.ToString().Trim());
                    int ssss = Nonzero + 1;
                    length = temp.Length - ssss.ToString().Length;
                    string mo = (temp.Substring(0, length) + ssss.ToString());
                    //temp = table.Rows[0][0].ToString().Trim();
                    //Nonzero = Convert.ToInt32(table.Rows[0][0].ToString().Trim());
                    //int ssss = Nonzero + 1;
                    //length = temp.Length - ssss.ToString().Length;
                    //string mo = (temp.Substring(0, length) + ssss.ToString());

                    return yearAndMonth + mo;
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Cann't Create Next Id", exception);
            }
            finally
            {
                if (ConnectionObj != null && ConnectionObj.State == ConnectionState.Open)
                {
                    ConnectionObj.Close();
                }
            }
        }


    }
}